﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Arch.Samples.Mvc.Infrastructure
{
    public class CrudControllerBase<T> : ControllerBase where T : class, new()
    {
        public virtual ActionResult Index()
        {
            return View(Repository.Find<T>());
        }

        public virtual ActionResult Details(int id)
        {
            return View(Repository.Load<T>(id));
        }

        public virtual ActionResult Create()
        {
            var entity = Repository.New<T>();
            LoadDependencies(entity);
            return View(entity);
        }

        [HttpPost]
        public virtual ActionResult Create(FormCollection collection)
        {
            var entity = Repository.New<T>();
            try
            {
                UpdateModel(entity, excludes: new[] {"Id"});
                Repository.Create(entity);
                return RedirectToAction("Index");
            }
            catch
            {
                LoadDependencies(entity);
                return View();
            }
        }

        public virtual ActionResult Edit(int id)
        {
            var entity = Repository.Load<T>(id);
            LoadDependencies(entity);
            return View(entity);
        }

        [HttpPost]
        public virtual ActionResult Edit(int id, FormCollection collection)
        {
            var entity = Repository.Load<T>(id);
            try
            {
                UpdateModel(entity, excludes: new[] { "Id" });
                Repository.Update(entity);
                return RedirectToAction("Index");
            }
            catch
            {
                LoadDependencies(entity);
                return View();
            }
        }

        public virtual ActionResult Delete(int id)
        {
            return View(Repository.Load<T>(id));
        }

        [HttpPost]
        public virtual ActionResult Delete(int id, FormCollection collection)
        {
            Repository.Delete(Repository.Load<T>(id));
            return RedirectToAction("Index");
        }

        protected virtual void LoadDependencies(T entity)
        {

        }
    }
}